<?php

namespace App\Http\Controllers\Admin;
//接口账号表
use App\Models\Apiuser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ApiuserController extends Controller
{
    //接口账号列表
    public function index()
    {
        $data = Apiuser::withTrashed()->get();;
        return view('admin.apiuser.index',compact('data'));
    }

    //添加 显示
    public function create()
    {
        return view('admin.apiuser.create');
    }

    //添加 处理
    public function store(Request $request)
    {
        //表单验证
        try {
            $data = $this->validate($request,[
                'username'  =>  'required|unique:apiusers,username',
                'password'  =>  'required'
            ]);
        }catch (\Exception $e){
            return ['status' => 1000,'msg' => '账号名已存在'];
        }
        //入库
        Apiuser::create($data);
        return  ['status' => 0,'msg' => '添加成功'];
    }

    //
    public function rest(int $id)
    {
        Apiuser::onlyTrashed()->where('id',$id)->restore();
        return ['status' =>0,'msg'=>'恢复成功'];
    }

    //修改 显示
    public function edit(Apiuser $apiuser)
    {
        return view('admin.apiuser.edit',compact('apiuser'));
    }

    //修改 处理
    public function update(Request $request, Apiuser $apiuser)
    {
        try {
            $data = $this->validate($request,[
                'password'  => 'required'
            ]);
        }catch (\Exception $e){
            return['status' => 1000,'msg' => '密码不能为空'];
        }

        if($apiuser->username == 'admin'){
            return ['status' => 1000,'msg'=> '不可修改'];
        }else{
            $apiuser->update($data);
            return ['status' =>0,'msg' => '修改密码成功'];
        }

    }

    //删除
    public function destroy(Apiuser $apiuser)
    {
        $apiuser->delete();
        return ['status' => 0,'msg' =>'删除成功'];
    }
}
